package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiDuMapProperties;
import com.sky.properties.WeChatProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class BaiDuMapUtils {


    @Autowired
    private BaiDuMapProperties baiDuMapProperties;

    /**
     * 百度地图接口(获取全部返回信息)
     * @return
     * @throws Exception
     */
    public String baiDuMapGet(String location) throws Exception {

        Map params = new LinkedHashMap<String, String>();
        params.put("address", location);
        params.put("output", "json");
        params.put("ak", baiDuMapProperties.getAk());

        String res = requestGetAK(baiDuMapProperties.getUrl(), params);
        if (res == null) {
            throw new Exception("百度地图api调用出错");
        } else {
            return res;
        }
    }




    private String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        String res = buffer.toString();
        // 如果返回的是JSONP格式，需要处理掉函数调用的包装
        if (res.startsWith("showLocation")) {
            res = res.substring(res.indexOf("(") + 1, res.lastIndexOf(")"));
        }
        return res;
    }
}
